'use strict';
const dayjs = require("dayjs");

module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT } = app.Sequelize;
  
  const Roles = app.model.define(
    'Roles',
    {
      id: { type: INTEGER, primaryKey: true, autoIncrement: true },
      name: { type: STRING(50), allowNull: false, unique: true },
      description: { type: STRING(255) },
      status: { type: INTEGER, defaultValue: 1 },
      create_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('create_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      update_time: {
        type: DATE,
        get() {
          return dayjs(this.getDataValue('update_time')).format('YYYY-MM-DD HH:mm:ss');
        }
      }
    },
    {
      tableName: 'roles',
      timestamps: true,
      createdAt: 'create_time',
      updatedAt: 'update_time'
    }
  );

  Roles.associate = function() {
    app.model.Roles.hasMany(app.model.Users, { foreignKey: 'role_id', as: 'users' });
    app.model.Roles.belongsToMany(app.model.Permissions, { 
      through: app.model.RolePermissions,
      foreignKey: 'role_id',
      otherKey: 'permission_id',
      as: 'permissions'
    });
  };

  return Roles;
};
